#
# Copyright (C) Since 2018 ~ 2025, Inc. All Rights Reserved
#
# @Time    : 2025/1/8-下午9:14
# @Author  : Timmy
# @Email   : tangping@cloudstream-tech.com
# @File    : create_activity_dialog.py
# @Software: lottery
# @Function:
#
import asyncio
import os
from concurrent.futures import ThreadPoolExecutor

import aiofiles
from PyQt5.QtCore import QDate
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QDialog, QHeaderView, QFileDialog, QPushButton
from qasync import asyncSlot

from models.types import Activity, Award, People
from ui.wnd_create_activity import Ui_CreateActivityDialog


class CreateActivityDialog(QDialog, Ui_CreateActivityDialog):
    def __init__(self, parent=None, activity: Activity = None):
        super(CreateActivityDialog, self).__init__(parent)
        self.setupUi(self)

        # 注册“控件”事件处理函数
        self.pushButton_openFile.clicked.connect(self._on_btn_openfile)
        self.pushButton_addAward.clicked.connect(self._on_btn_add_award)
        self.pushButton_saveActivity.clicked.connect(self._on_btn_save_activity)
        self.pushButton_addPeople.clicked.connect(self._on_btn_add_people)
        self.pushButton_deleteActivity.clicked.connect(self._on_btn_delete_activity)

        # "控件"初始化
        self.dateEdit_activityDate.setDate(QDate.currentDate())

        # 初始化 tableview
        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(['名称', '奖品', '数量', ''])
        self.tableView_awards.setModel(model)
        header = self.tableView_awards.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeToContents)
        header.setMaximumHeight(20)

        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(['姓名', '部门', '身份', 'α', ''])
        self.tableView_peopleList.setModel(model)
        header = self.tableView_peopleList.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeToContents)
        header.setMaximumHeight(20)

        # 数据定义
        self._last_dir = os.path.join(os.path.expanduser("~"), 'Desktop')
        self.activity = Activity()
        if activity is not None:
            self.activity = activity
            self.lineEdit_activityName.setText(activity.name)
            self.dateEdit_activityDate.setDate(activity.date)

            # 初始化奖项
            for idx, award in enumerate(activity.awards.values()):
                self._award_list_add_row(award)

            # 初始化名单
            for idx, people in enumerate(activity.people.values()):
                self._people_list_add_row(people)

            self.label_peopleTotal.setNum(len(activity.people))
            self.label_rateTotal.setText('%s%%' % self.activity.get_rate_total())

        # self.executor = ThreadPoolExecutor(max_workers=1)

    @asyncSlot()
    async def _on_btn_openfile(self):
        def open_func():
            return QFileDialog.getOpenFileName(
                self,
                "选择名单文件",
                self._last_dir,
                "*.csv"
            )

        filename = await asyncio.to_thread(open_func)

        if not filename or not filename[0]:
            return

        filepath = filename[0]
        await self._open_namelist_file(filepath)

    async def _open_namelist_file(self, filepath: str):
        print(filepath)
        self._last_dir = os.path.dirname(filepath)

        model = self.tableView_peopleList.model()
        model.removeRows(0, model.rowCount())
        self.activity.people = {}

        namelist: list[People] = []
        counter = 0
        async with aiofiles.open(filepath, 'r') as f:
            async for line in f:
                if counter == 0:
                    counter += 1
                    continue

                line = line.strip()
                row = line.split(',')[:4]
                row[3] = int(row[3])
                people = People(*row)
                self._people_list_add_row(people)
                namelist.append(people)
                counter += 1

        await self.activity.add_people(namelist)
        self.label_peopleTotal.setNum(len(self.activity.people))
        self.label_rateTotal.setText('%s%%' % self.activity.get_rate_total())

    def _on_namelist_delete_clicked(self):
        sender = self.sender()
        loop = asyncio.get_event_loop()
        loop.create_task(self._delete_people(sender.property('id')))

    async def _delete_people(self, row_id: int):
        # delete from db
        model = self.tableView_peopleList.model()
        name = model.item(row_id, 0).text()
        await self.activity.del_people(name)
        model.removeRow(row_id)

        self.label_peopleTotal.setNum(model.rowCount())
        self.label_rateTotal.setText('%s%%' % self.activity.get_rate_total())

    @asyncSlot()
    async def _on_btn_add_award(self):
        name = self.lineEdit_awardName.text()
        content = self.lineEdit_awardContent.text()
        number = self.spinBox_awardNumber.value()
        print(name, content, number, type(number))

        # 添加到 模型
        award = Award(name, content, number)
        self._award_list_add_row(award)
        await self.activity.add_award(award)

    def _award_list_add_row(self, award: Award):
        model = self.tableView_awards.model()
        row_idx = model.rowCount()
        model.setItem(row_idx, 0, QStandardItem(award.name))
        model.setItem(row_idx, 1, QStandardItem(award.content))
        model.setItem(row_idx, 2, QStandardItem(str(award.count)))

        delete_btn = QPushButton("删除", self)
        delete_btn.setMaximumWidth(60)
        delete_btn.setProperty("id", row_idx)
        delete_btn.clicked.connect(self._on_award_list_delete_clicked)
        self.tableView_awards.setIndexWidget(model.index(row_idx, 3), delete_btn)
        self.tableView_awards.setRowHeight(row_idx, 18)

    def _on_award_list_delete_clicked(self):
        sender = self.sender()
        row_id = sender.property('id')
        print(row_id)

        # 从model 中删除
        loop = asyncio.get_event_loop()
        loop.create_task(self._delete_award(row_id))

    async def _delete_award(self, row_id: int):
        model = self.tableView_awards.model()
        name = model.item(row_id, 0).text()
        model.removeRow(row_id)

        await self.activity.del_award(name)

    @asyncSlot()
    async def _on_btn_add_people(self):
        name = self.lineEdit_peopleName.text()
        dep = self.comboBox_peopleDep.currentText()
        ide = self.comboBox_peopleIdentity.currentText()
        alpha = self.comboBox_peopleAlpha.currentText()
        print(name, dep, ide, alpha)
        people = People(name, dep, ide, int(alpha))
        await self.activity.add_people([people])
        self._people_list_add_row(people)

    def _people_list_add_row(self, people: People):
        model = self.tableView_peopleList.model()
        row_idx = model.rowCount()
        model.setItem(row_idx, 0, QStandardItem(people.name))
        model.setItem(row_idx, 1, QStandardItem(people.dep))
        model.setItem(row_idx, 2, QStandardItem(people.identity))
        model.setItem(row_idx, 3, QStandardItem(str(people.alpha)))

        delete_btn = QPushButton("删除", self)
        delete_btn.setMaximumWidth(60)
        delete_btn.setProperty("id", row_idx)
        delete_btn.clicked.connect(self._on_namelist_delete_clicked)
        self.tableView_peopleList.setIndexWidget(model.index(row_idx, 4), delete_btn)
        self.tableView_peopleList.setRowHeight(row_idx, 20)

    @asyncSlot()
    async def _on_btn_save_activity(self):
        act_name = self.lineEdit_activityName.text()
        act_date = self.dateEdit_activityDate.date().toPyDate()
        self.activity.name = act_name
        self.activity.date = act_date
        await self.activity.save_db()
        self.label_status.setText("保存成功")

    @asyncSlot()
    async def _on_btn_delete_activity(self):
        if self.activity.name:
            await self.activity.delete()
            self.label_status.setText("删除成功")